﻿<template>
  <div id="app">
    <div id="loading" v-show="shopShow">正在加载出租车数据...</div>
    <div id="menuLeft">
      <div id="step1">
        <h4>点数据选择：</h4>
        <el-cascader
            ref="getSelectData"
            placeholder="请选择需要渲染的数据"
            v-model="dataValue"
            :options="options"
            @change="handleSelectChange"
            filterable></el-cascader>
        <el-button @click="addAggregationAuto" :disabled="isDisabled">加载</el-button>
        <el-button @click="clear">清除</el-button>
      </div>
      <div id="step2">
        <h4>面数据选择：</h4>
        <el-select v-model = "sysFileId" placeholder = "请选择Shp数据" @change = "selectFileName()" class = "selectShp">
          <el-option v-for = "item in this.fileNameList" :key = "item.id" :label = "item.name" :value = "item.id"></el-option>
        </el-select>
        <el-button @click="clearShp">清除</el-button>
      </div>
    </div>

    <div id="map_auto" :style="{height:'100%', width:'100%'}" v-if="displayAutonavi"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";

let cluster_auto, map_auto, polygonLayer, loca;

export default {
  data() {
    return {
      isDisabled: true,
      shopShow: false,
      map: null,
      sysFileId:"",
      fileNameList:[],
      mapLng: 116.403,
      mapLat: 39.923,
      mapZoom: 12, //缩放比列
      options: this.$store.state.dataPoint[0].children,
      dataValue: [],
      taxiData: [],
      //高德数据
      clusterData1: [],
      //百度数据
      clusterData2: [],
      heatmapLayer: null,
      displayAutonavi: true,
      view:{},
      downSelectData: '',
    }
  },
  mounted() {
    this.initFileName()
    //初始化高德地图
    this.initAutonavi()
  },
  created() {
    this.$store.commit('loadMenuDataPoint')
  },
  methods: {
    handleSelectChange(val){
      this.shopShow = true
      this.isDisabled = true
      let downSelectData = this.$refs.getSelectData.getCheckedNodes()
      this.downSelectData = downSelectData[0].data.value
      console.log(this.downSelectData,'获取下拉节点的值');
      this.request.get("/taxiData/clickHot",
          {
            params:{
              downSelectData: this.downSelectData,
            }
          },
      ).then(res => {
        console.log(res.data)
        this.clusterData1 = []
        //开始组装数据，组装成geojson格式的数据
        for (let i = 0; i < res.data.length; i++) {
          //高德数据组装
          this.clusterData1.push(
              {
                lnglat: [res.data[i].lng, res.data[i].lat]
              }
          )
        }
        this.shopShow = !this.shopShow
        this.isDisabled = !this.isDisabled
        console.log(this.clusterData1,"初始数据加载完毕！")
      })
    },
    initFileName() {
      this.request.get("/file/page",
          {
            params:{
              pageNum: 1,
              pageSize: 99
            }
          },
      ).then(res => {
        console.log(res.data);
        this.fileNameList = [];
        this.fileNameList = res.data.records;
        console.log(this.fileNameList, "this.fileNameList");
        this.total = res.data.total;
      })
    },
    selectShpFile(){
      this.request.post("/file/byid/" + this.sysFileId,
          {
            params:{
              pageNum: 1,
              pageSize: 99
            }
          },
          {
            responseType: "blob"
          }
      ).then(res => {
        // console.log(res);
        console.log("res.data");
        // this.shpFile = res;
        this.shpFile = new Blob([res]);
        let fileReader = new FileReader();
        // 将文件读取为二级制码
        // fileReader.readAsArrayBuffer(this.shpFile);
        let that = this
        fileReader.onload = function() {
          // 获取读取的结果
          // console.log(this.result,'js的文件读取结果');
          let shapefile = require("shapefile")
          shapefile.read(this.result).then(geoJson => {
            console.log(geoJson,'geoJson数据开始进行变换');
            // 创建数据源
            var dataSource = new Loca.GeoJSONSource({
              data: geoJson,
            });
            console.log(dataSource, "dataSource")
            // 图层添加数据
            polygonLayer.setSource(dataSource);
            // 设置样式
            polygonLayer.setStyle({
              topColor: 'rgba(255,255,255,0.3)',
            })
          })
          // 添加到地图上
          loca.add(polygonLayer);
        }

        fileReader.readAsArrayBuffer(this.shpFile);
      })

    },
    selectFileName(){
      this.selectShpFile();
    },
    clearShp(){
      loca.remove(polygonLayer)
    },
    // 高德初始化
    initAutonavi() {
      AMapLoader.load({
        key: "3b20e3a90d6b5fdd4d073285823e4ab5", //key值是key值 和安全密钥不同
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.MarkerCluster'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "Loca": {  //是否加载 Loca,缺省不加载
          "version": '2.0.0'  //Loca 版本,缺省1.3.2
        }
      })
          .then((AMap) => {
            // 初始化地图
            map_auto = new AMap.Map("map_auto", {
              viewMode: "3D", //  是否为3D地图模式
              zoom: 11.4, // 初始化地图级别
              center: [116.404582, 39.90359], //中心点坐标
              resizeEnable: true,
              //设置地图样式
              // mapStyle: 'amap://styles/029d1d7e79696c27eb2ab6f4d056d186'
              mapStyle: 'amap://styles/dark'
            });

            //输入提示
            let autoOptions = {
              input: "tipinput"
            };

            AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
              let auto = new AMap.AutoComplete(autoOptions);
              let placeSearch = new AMap.PlaceSearch({
                map: map_auto
              });  //构造地点查询类
              auto.on("select", select);//注册监听，当选中某条记录时会触发
              function select(e) {
                placeSearch.setCity(e.poi.adcode);
                placeSearch.search(e.poi.name);  //关键字查询查询
              }
            });
            // 创建 Loca 实例
            loca = new Loca.Container({
              map: map_auto
            });
            //创建面图层
            polygonLayer = new Loca.PolygonLayer({
              loca: loca,
              zooms: [2, 20],
              zIndex: 10,
              visible: true,
              opacity: 1,
              cullface: 'back',
              acceptLight: true,
              shininess: 30,
              hasSide: true,
              depth: true,
            })
          })

    },
    addAggregationAuto(){
      this.displayAutonavi = true
      let that = this
      let count = that.clusterData1.length

        setTimeout(() => {
          let gridSize = 60
          let _renderClusterMarker = function (context) {
            let factor = Math.pow(context.count / count, 1 / 18);
            let div = document.createElement('div');
            let Hue = 180 - factor * 180;
            let bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
            let fontColor = 'hsla(' + Hue + ',100%,90%,1)';
            let borderColor = 'hsla(' + Hue + ',100%,40%,1)';
            let shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
            div.style.backgroundColor = bgColor;
            let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
            div.style.width = div.style.height = size + 'px';
            div.style.border = 'solid 1px ' + borderColor;
            div.style.borderRadius = size / 2 + 'px';
            div.style.boxShadow = '0 0 5px ' + shadowColor;
            div.innerHTML = context.count;
            div.style.lineHeight = size + 'px';
            div.style.color = fontColor;
            div.style.fontSize = '14px';
            div.style.textAlign = 'center';
            context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
            context.marker.setContent(div)
          };
          let _renderMarker = function (context) {
            let content = '<div style="background-color: hsla(180, 100%, 50%, 0.3); height: 18px; width: 18px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 3px;"></div>';
            let offset = new AMap.Pixel(-9, -9);
            context.marker.setContent(content)
            context.marker.setOffset(offset)
          }
          addCluster();

          function addCluster() {
            if (cluster_auto) {
              cluster_auto.setMap(null);
            }
            cluster_auto = new AMap.MarkerCluster(map_auto, that.clusterData1, {
              gridSize: gridSize, // 设置网格像素大小
              renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
              renderMarker: _renderMarker, // 自定义非聚合点样式
            });
          }
        },0)
      // })
     },

    clear(){
      if(cluster_auto != null){
        console.log("销毁高德");
        cluster_auto.setMap(null);
      }
    }
  },
  beforeDestroy() {
    this.$store.commit('refresh')
  }
}
</script>

<style scoped>
#app{
  position: relative;
  height:100%;
  width:100%;
}
#loading {
  z-index: 99;
  position:absolute;
  top: 50%;
  left: 48%;
  margin-left: -130px;
  text-align: center;
  margin-top: -50px;
  width: 280px;
  padding: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: yellow;
  font-size: 20px;
}
#menuLeft {
  position: absolute;
  top: 20px;
  left: 12px;
  width: 24%;
  height: 22%;
  z-index: 100;
  font-size: 20px;
  font-weight: 700;
  color: white;
  background-color: rgba(49, 51, 53, 0.7);
  background-image: url("../../assets/image/public_resource/border_new1.png");
  background-size: 100% 100%;
  /*opacity: 0.8;*/
  border-radius: 20px;
  overflow: auto;
}
h4{
  margin-top: 10px;
  margin-bottom: 10px;
}
#step1{
  margin-left: 30px;
}
#step2{
  margin-left: 30px;
}
.selectShp{
  left: 0;
  top: 0;
}
#VisualShow{
  margin-left: 30px;
}
</style>